package show.me.the.money.resource;

import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

public class CompressScriptFile extends ResourceFile{
	private CharArrayWriter arrayWriter;
	private String encoding = "GBK";//"Cp1252";
	File file;
	public void setFileName(String fileName){
		file = new File(fileName);
		
		exists = file.exists();
	}
	public void load() throws IOException{
		if(exists && file.lastModified() != lastModi){
			lastModi = file.lastModified();
			InputStreamReader in = new InputStreamReader(new FileInputStream(file),encoding);
			JavaScriptCompressor jsc =getJSC(in);
			if(arrayWriter == null){
				arrayWriter = new CharArrayWriter();
			}
			else{
				arrayWriter.reset();
			}
			jsc.compress(arrayWriter, -1, true, true, false, false);
		}		
	}

	public int length(){
		if(arrayWriter == null){
			return 0;
		}
		return  arrayWriter.size();
	}
	
	public boolean exists(){
		return exists;
	}
	
	public String toString(){
		return arrayWriter.toString();
	}
	
	public InputStream getInputStream(){
		return null;
	}
	
	public void writeToStream(OutputStream outs,boolean needClose) throws IOException{
	   if(arrayWriter != null){
		    OutputStreamWriter out = new OutputStreamWriter(outs,encoding);
		    arrayWriter.writeTo(out);
	    	out.write("\n");
	    	out.flush();
	    	if(needClose){
	    		out.close();
	    	}
	    }
	}
	
	private JavaScriptCompressor getJSC(InputStreamReader in) throws EvaluatorException, IOException{
		return new JavaScriptCompressor(in, new ErrorReporter() {
			public void warning(String message, String sourceName,int line, String lineSource, int lineOffset) {
                
            }

            public void error(String message, String sourceName,int line, String lineSource, int lineOffset) {
            	if (line < 0) {
                    System.err.println("\n[ERROR] " + message);
                } else {
                    System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':' + message);
                }
            }

            public EvaluatorException runtimeError(String message, String sourceName,int line, String lineSource, int lineOffset) {
                return new EvaluatorException(message);
            }
        });
	}
}
